#!/bin/bash
# Copyright (c) 2000-2016 Synology Inc. All rights reserved.

if [ -z "$__INCLUDE_INSTALL__" ]; then
__INCLUDE_INSTALL__=defined

Source include/config
Source include/check
Source include/platforms
Source include/applyEnv
BUILD_TARGET=""

PlatformOpts=`AllPlatformOptionsComma`
DefaultLongArgs="${PlatformOpts}platform:,with-debug,help"
DefaultArgs="dhp:"
IsDebugBuild="N"
DebType="bin"

ParseDefaultInstallArgs(){
UnHandledOpt=
while [ -n $1 ]; do
	IsPlatformOption $1
	if [ $? -eq 0 ]; then
		AskPlatform $1
	else
		case "$1" in
		# platforms
		"-p" | "--platform")
			AskPlatform "--$2"
			shift
			;;
		"-d" | "--with-debug")
			export NOSTRIP="NOSTRIP"
			IsDebugBuild="Y"
			;;
		"--help" | "-h")
			Usage
			exit 0
			;;
		"--")
			# remaining are project names
			shift
			break
			;;
		*)
			[ -n "$UnHandledOpt" ] && UnHandledOpt="$UnHandledOpt $1" || UnHandledOpt="$1"
			shift
			if [ "$1" = '--' ]; then
				shift
				break
			elif [[ "$1" =~ "-" ]]; then
				continue
			else
				UnHandledOpt="$UnHandledOpt $1"
			fi
			;;
		esac
	fi
	shift
done

InputProjs=$@

if [ -z "$BUILD_OPT" ]; then
	# call again without parameters
	# to prompt user interactively
	AskPlatform
fi
}

SetupInstallEnv(){
	local debugBuild=$1

	SetupDSMBuildNumber
	LoadPlatformRelated || exit 1

	if [ "Y" = "$debugBuild" ]; then
		TarBallDir=$DebugTarBallDir
		DebType="debug"
	fi

	mkdir -p ${TarBallDir} $LogDir $TmpInstDir
	[ -d "$DebPkgDir" ] || mkdir -p $DebPkgDir
}

UnifyInstallProjects() {
	local projectList=

	for proj in $@; do
		projectList="${projectList} `basename ${proj}`"
	done

	echo $projectList
}

ExcludeProjects() {
	local projList=$@
	local retProjs=

	retProjs=$(ExcludeList "$projList" "$(getPlatformExcludeProjs)")
	BuildMachineOnly || retProjs=$(ExcludeList "$retProjs" ".*-virtual-protection dsm-Protection")
	echo $retProjs
}

InstallProject() {
	local proj=$1
	local baseProj="${proj}"
	local installScript=

	cd $SourceDir/$baseProj
	CheckErrorOut $? "Failed to cd $SourceDir/$baseProj"
	if ! installScript=$(findInstallScript "${proj}"); then
		ERROR "There is no install scripts for $proj"
		return 1
	fi

	INFO "Execute install script: $installScript"
	(. $installScript)

	CheckProjectStatus install $proj > /dev/null

	return $?
}

SetupProjInstallEnv() {
	local proj=$1

	if Is64BitProject "${proj}"; then
		INFO "ENV" "Using 64bit environment."
		ApplyInstallEnv "64"
	else
		INFO "ENV" "Using 32bit environment."
		ApplyInstallEnv "32"
	fi

	rm -rf $TmpInstDir/*
}

CreateTarball() {
	local proj=$1
	local haveFile=`ls $TmpInstDir`

	if [ ! -z "$haveFile" ]; then
		echo ""
		echo "Create ${proj}.txz ..."
		( cd "$TmpInstDir"; XZ_OPT=-3 tar cJpvf "$TarBallDir/${proj}.txz" * )
		echo "[Done]"
	else
		INFO "WARNING" "$TmpInstDir is empty!"
	fi

}

InstallPreparePkgDir() # $1: Target Dir $2: Dir list
{
	TargetDir="$1"
	for dirmode in $2
	do
		DIR=`echo ${dirmode} | cut -f1 -d':'`	
		MODE=`echo ${dirmode} | cut -f2 -d':' -s`	
		if [ -n "${MODE}" ]; then
			MODE_ARG="-m ${MODE}"
		fi
		echo "mkdir -p ${MODE_ARG} $TargetDir/${DIR}"
		mkdir -p ${MODE_ARG} $TargetDir/${DIR}
	done
}

InstallPkgFiles() # $1: Target Dir $2: Path $3: Default mode $4: FileList
{
	PrefixDir="$1/$2"
	DefMode="$3"
	[ -n "$4" ] && mkdir -p "${PrefixDir}"
	for file in $4
	do
		FileBase=$(echo "$file" | cut -f1 -d':')
		FileDS=$(echo "$file" | cut -f2 -d':' -s)
		if [ -z "$FileDS" ]; then
		    FileInst="$PrefixDir/$FileDS/$(basename "$FileBase")"
		else
		    FileInst="$PrefixDir/$FileDS"
		fi

		if [ ! -f "$FileBase" ]; then
			echo "Error: $FileBase not found!"
			continue
		fi

		install -vm "$DefMode" "$FileBase" "$FileInst" | grep -- "->"
		RetInstall=$?
		if [ $RetInstall -ne 0 ]; then
			echo "Error: [install -vm $DefMode $FileBase $FileInst], ret=$RetInstall"
			continue
		fi

		file "${FileInst}" | grep ELF > /dev/null 2>&1
		if [ $? -eq 0 -a "x$NOSTRIP" != "xNOSTRIP" ]; then
			echo "Striping ${FileInst}"
			${STRIP} -s --remove-section=.note --remove-section=.comment "$FileInst"
		fi
	done
}

InstallPrepareDir() # $1: Dir list
{
	InstallPreparePkgDir "$TmpInstDir" "$@"
}

InstallFiles() # $1: Path $2: Default mode $3: FileList
{
	InstallPkgFiles "$TmpInstDir" "$@"
}

DoInstall()
{
	InstallPrepareDir "${INSTALL_DIRS}"

	InstallFiles $LibDir 755 "${INSTALL_LIB}"
	InstallFiles "/bin" 755 "${INSTALL_BIN}"
	InstallFiles "/sbin" 755 "${INSTALL_SBIN}"
	InstallFiles "/usr/bin" 755 "${INSTALL_USR_BIN}"
	InstallFiles "/usr/sbin" 755 "${INSTALL_USR_SBIN}"
	InstallFiles "/usr/syno/bin" 755 "${INSTALL_SYNO_BIN}"
	InstallFiles "/usr/syno/sbin" 755 "${INSTALL_SYNO_SBIN}"
	InstallFiles "/usr/syno/etc/rc.d" 755 "${INSTALL_RCD}"
	InstallFiles "/etc" 644 "${INSTALL_ETC}"
	InstallFiles "/etc/pam.d/" 644 "${INSTALL_PAM}"
	InstallFiles "/usr/syno/etc" 644 "${INSTALL_SYNO_ETC}"
	InstallFiles "/usr/local/bin" 755 "${INSTALL_LOCAL_BIN}"
	InstallFiles "/usr/local/sbin" 755 "${INSTALL_LOCAL_SBIN}"
	InstallFiles "/usr/local/etc/rc.d" 755 "${INSTALL_LOCAL_RCD}"
	InstallFiles "/usr/local/etc" 644 "${INSTALL_LOCAL_ETC}"
}

is_support_apparmor() {
	SupportAppArmorPlatform
}

_create_empty_tgz() {
	touch ${TarBallDir}/${ThisProj}.tar
	gzip ${TarBallDir}/${ThisProj}.tar
	mv ${TarBallDir}/${ThisProj}.tar.gz ${TarBallDir}/${ThisProj}.tgz
}

_create_empty_txz() {
	tar cJf "$TarBallDir/${ThisProj}.txz" --files-from /dev/null
}

SkipThisProject() {
	_create_empty_txz
}

fi
# vim: ft=sh
